import request from '@/utils/request'
import { getToken } from '@/utils/auth'

// 通用文件上传
export function upload(data, onProgress) {
  return request({
    url: '/common/upload',
    method: 'post',
    timeout: 1000 * 60 * 30, // 30分钟超时
    data: data,
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': 'Bearer ' + getToken()
    },
    // 上传进度
    onUploadProgress: progressEvent => {
      const complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
      console.log('上传进度：' + complete + '%')
      if (onProgress && typeof onProgress === 'function') {
        onProgress(progressEvent)
      }
    },
    // 允许跨域携带cookie信息
    withCredentials: true,
    // 定义上传类型为blob
    responseType: 'blob',
    transformRequest: [function (data) {
      return data
    }],
    transformResponse: [function (data) {
      if (typeof data === 'string') {
        try {
          data = JSON.parse(data)
        } catch (e) {
          console.log('响应数据格式转换失败', e)
        }
      }
      return data
    }]
  })
} 